﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JasLib.Extensions
{
    /// <summary>
    /// These methods simplify the use of a one-key-to-many-values Dictionary as a 
    /// replacement for the more cumbersome NameValueCollection.
    /// </summary>
    public static class PseudoNameValueCollectionExtensions
    {
        /**********************************************************************************/
        public static void AddToValueSet<TKey, TValue, TSet>(
            this IDictionary<TKey, TSet> dictionary,
            TKey key,
            params TValue[] values)
            where TSet : ISet<TValue>, new()
        {
            TSet set;
            if (!dictionary.TryGetValue(key, out set))
            {
                set = new TSet();
                dictionary.Add(key, set);
            }
            set.AddRange(values);
            return;
        }

        /**********************************************************************************/
        /// <summary>
        /// JAS: I can't seem to make this work with ISet instead of HashSet.
        /// </summary>
        public static TValue FirstFromValueSetOrDefault<TKey, TValue>(
            this IDictionary<TKey, HashSet<TValue>> dictionary,
            TKey key)
        {
            HashSet<TValue> set;
            if (!dictionary.TryGetValue(key, out set))
                return default(TValue);

            return set.FirstOrDefault();
        }

        /**********************************************************************************/
        public static void RemoveFromValueSet<TKey, TValue, TSet>(
            this IDictionary<TKey, TSet> dictionary,
            TKey key,
            params TValue[] values)
            where TSet : ISet<TValue>, new()
        {
            TSet set;
            if (!dictionary.TryGetValue(key, out set))
                return;

            for (int iIndex = 0; iIndex < values.Length; iIndex++)
                set.Remove(values[iIndex]);

            if (set.Count == 0)
                dictionary.Remove(key);
            return;
        }

        /**********************************************************************************/
        public static void OverwriteValueSet<TKey, TValue, TSet>(
            this IDictionary<TKey, TSet> dictionary,
            TKey key,
            params TValue[] values)
            where TSet : ISet<TValue>, new()
        {
            TSet set;
            if (!dictionary.TryGetValue(key, out set))
            {
                set = new TSet();
                dictionary.Add(key, set);
            }
            else
            {
                set.Clear();
            }
            set.AddRange(values);
            return;
        }
    }
}
